package com.freesky.biz.rights.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.freesky.biz.activity.domain.TSettlement;
import com.freesky.biz.activity.domain.TSettlementDetail;
import com.freesky.biz.rights.domain.ArrearsDetailEntity;
import com.freesky.biz.rights.domain.ArrearsFileEntity;
import com.freesky.biz.rights.domain.EncryptBatchEntity;
import com.freesky.biz.rights.pojo.EncryptCodePo;
import com.freesky.biz.rights.service.IArrearsFileService;
import com.freesky.biz.rights.service.IEncryptBatchService;
import com.freesky.biz.utils.SeqUtil;
import com.freesky.common.annotation.Log;
import com.freesky.common.core.controller.BaseController;
import com.freesky.common.core.domain.AjaxResult;
import com.freesky.common.core.page.TableDataInfo;
import com.freesky.common.enums.BusinessType;
import com.freesky.common.exception.base.BaseException;
import com.freesky.common.utils.SecurityUtils;
import com.freesky.common.utils.StringUtils;
import com.freesky.common.utils.file.OssUtils;
import com.freesky.common.utils.poi.ExcelUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;

/**
 * 补发文件上传管理（批量）
 */
@RestController
@RequestMapping("/rights/arrears/file")
public class ArrearsFileController extends BaseController {

    @Autowired
    private IArrearsFileService arrearsFileService;

    @Autowired
    private OssUtils ossUtils;

    @Value("${oss.host}")
    private String host;

    /**
     * 分页获取批次
     */
    @PreAuthorize("@ss.hasPermi('arrears:file:list')")
    @GetMapping("/page")
    public TableDataInfo page(ArrearsFileEntity entity) {
        IPage<EncryptBatchEntity> pageList = arrearsFileService.selectFilePage(plusPage(),entity);
        return getDataTable(pageList);
    }

    /**
     * 根据id获取详细信息
     */
    @PreAuthorize("@ss.hasPermi('arrears:file:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable String id) {
        return success(arrearsFileService.getById(id));
    }


    @PreAuthorize("@ss.hasPermi('arrears:file:add')")
    @Log(title = "补发文件上传", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody ArrearsFileEntity entity) {
        if(!StringUtils.isEmpty(entity.getName())) {
            return AjaxResult.error("新增补发文件标题不能为空!");
        }
        entity.setId(SeqUtil.getSeqId());
        entity.setDelFlag("0");
        entity.setStatus("0");
        entity.setCreateBy(String.valueOf(SecurityUtils.getLoginUser().getUserId()));
        entity.setCreateTime(new Date());
        return toAjax(arrearsFileService.save(entity));
    }

    @PreAuthorize("@ss.hasPermi('arrears:file:edit')")
    @Log(title = "补发文件上传", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody ArrearsFileEntity entity) {
        ArrearsFileEntity queryData = arrearsFileService.getById(entity.getId());
        if(queryData == null) {
            return AjaxResult.error("记录不存在，无法修改!");
        }
        queryData.setName(entity.getName());
        //只能修改批次名称、状态
        queryData.setUpdateBy(String.valueOf(SecurityUtils.getLoginUser().getUserId()));
        queryData.setUpdateTime(new Date());
        return toAjax(arrearsFileService.updateById(queryData));
    }

    @PreAuthorize("@ss.hasPermi('arrears:file:audit')")
    @Log(title = "补发文件上传", businessType = BusinessType.UPDATE)
    @PutMapping("/audit")
    public AjaxResult audit(@Validated @RequestBody ArrearsFileEntity entity) {
        ArrearsFileEntity queryData = arrearsFileService.getById(entity.getId());
        if(queryData == null) {
            return AjaxResult.error("记录不存在，无法修改!");
        }
        ArrearsFileEntity updateData = new ArrearsFileEntity();
        updateData.setId(entity.getId());
        updateData.setStatus(entity.getStatus());
        //只能修改批次名称、状态
        updateData.setUpdateBy(String.valueOf(SecurityUtils.getLoginUser().getUserId()));
        updateData.setUpdateTime(new Date());
        return toAjax(arrearsFileService.updateById(updateData));
    }


    @PreAuthorize("@ss.hasPermi('arrears:file:remove')")
    @Log(title = "补发文件上传", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable List<String> ids) {
        return toAjax(arrearsFileService.deleteBatchByIds(ids.toArray(new String[0])));
    }


    @Log(title = "补发文件上传", businessType = BusinessType.IMPORT)
    @PreAuthorize("@ss.hasPermi('arrears:file:import')")
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file,
                                 String name) throws Exception {

        if(StringUtils.isEmpty(name)) {
            return AjaxResult.error("名称不能为空!");
        }

        String createBy = String.valueOf(SecurityUtils.getLoginUser().getUserId());

        Double totalAmt = 0.0;
        String batchId = SeqUtil.getSeqId();

        ExcelUtil<ArrearsDetailEntity> util = new ExcelUtil<>(ArrearsDetailEntity.class);
        List<ArrearsDetailEntity> arrearsDetailList = util.importExcel(file.getInputStream());
        System.out.println(JSON.toJSONString(arrearsDetailList));

        if(arrearsDetailList==null || arrearsDetailList.size()<=0){
            return AjaxResult.error("导入文件数据不能为空！");
        }

        List<ArrearsDetailEntity> batchList = new ArrayList<>();

        for(int i=0;i<arrearsDetailList.size();i++){
            ArrearsDetailEntity arrearsDetailEntity = arrearsDetailList.get(i);
            logger.info(JSON.toJSONString(arrearsDetailEntity));
            totalAmt = totalAmt + arrearsDetailEntity.getAmt();
            arrearsDetailEntity.setCreateBy(createBy);
            arrearsDetailEntity.setCreateTime(new Date());
            arrearsDetailEntity.setId(SeqUtil.getSeqId());
            arrearsDetailEntity.setBatchId(batchId);
            batchList.add(arrearsDetailEntity);
        }

        ArrearsFileEntity arrearsFileEntity = new ArrearsFileEntity();
        String suffixName = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        Random rand = new Random();
        String filePrefix = DateUtil.format(new Date(),"yyyyMM")+ File.separator + DateUtil.format(new Date(),"ddHHmmss") +"_"+String.valueOf(rand.nextInt(9999));

        String fileKey = filePrefix + suffixName;
        ossUtils.uploadFileStream(fileKey,file.getInputStream());

        AjaxResult ajax = AjaxResult.success("上传成功!");
        ajax.put("fileUrl", host + "/"+ fileKey);
        ajax.put("originalFilename", file.getOriginalFilename());

        arrearsFileService.batchAddArrearsDetail(batchList);

        arrearsFileEntity.setId(batchId);
        arrearsFileEntity.setName(name);
        arrearsFileEntity.setTotalMoney(String.valueOf(totalAmt));
        arrearsFileEntity.setTotalRecord(batchList.size());
        arrearsFileEntity.setOriFileName(file.getOriginalFilename());
        arrearsFileEntity.setUrl(host + "/"+ fileKey);
        arrearsFileEntity.setDelFlag("0");
        arrearsFileEntity.setCreateBy(createBy);
        arrearsFileEntity.setCreateTime(new Date());
        arrearsFileService.save(arrearsFileEntity);

        return ajax;
    }
}
